package com.honey.mybatis.generator.mappper;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.mybatis.generator.MybatisPlugin;

public class VirtualDeleteByDynamic extends AbstractMybatisMapper{

	public VirtualDeleteByDynamic(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		StringBuilder set = new StringBuilder();
		boolean bool =false ;
		for(Column column : introspectSchemaColumn.allColumns() ){
			String value = ((TableColumn)column).getVirtualDeleteValue();
			if( column instanceof TableColumn && value !=null){
				String key = column.getName();
				if( bool ){
					set.append(" , " );
				}else{
					bool = true ;
				}
				String c = column.isJdbcCharacterColumn()? "'": "";
				set.append( key)
				.append(" = ").append(c)
				.append(value).append(c);
			}
		}
		if( bool ){
			parent.addNewLine();
			parent.addComments(
					"按照组合条件虚拟删除记录, 更新\""+set.toString()+"\"."
			);
			XmlElement delete = new XmlElement(parent,"update")
			.addAttribute("id",MapperConstant.VIRTUAL_DELETE_BY_DYNAMIC_MAPPER_ID)
			.addAttribute("parameterType",super.getModelPrimitiveClassType(schema).getLongName())
			.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
			.addAttribute("flushCache", "true");
	
			delete.addTextElement("UPDATE " + schema.getName() +" SET "+ set.toString());
			
			new XmlElement(new XmlElement(delete,"if").addAttribute("test","_parameter != null"),
					"include").addAttribute("refid","dynamic.condition.defaultDynamic")
			;
		}
	}
}
